package com.wwy.order.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import com.common.domain.CommonResult;
import com.common.domain.MyException;
import com.common.domain.PageResult;
import com.common.enums.PayOrderStatusRespEnum;
import com.wwy.order.convent.ReportOrderConvert;
import com.wwy.order.domain.ConfirmRefundOrder;
import com.wwy.order.domain.ReportOrder;
import com.wwy.order.domain.vo.QueryOrderPageReq;
import com.wwy.order.domain.vo.ReportOrderCreateVo;
import com.wwy.order.domain.vo.ReportOrderRespVo;
import com.wwy.order.enums.ErrorCodeConstants;
import com.wwy.order.mapper.ReportOrderMapper;
import com.wwy.order.service.ReportOrderService;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import static com.common.utils.LocalDateTimeUtils.addTime;


/**
 * @author 王伟羽
 * @program: shuiwunew
 * @description:
 * @create: 2024/12/12
 */

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class ReportOrderServiceImpl implements ReportOrderService {

    @Resource
    private ReportOrderMapper reportOrderMapper;


    private static final String PAY_APP_ID = "7";
    /**
     * 定义订单号前缀，可以根据业务需求修改
     */
    private static final String PREFIX = "P";

    /**
     * 定义随机数长度
     */
    private static final int RANDOM_LENGTH = 6;

    /**
     * 定义一个同步锁对象，用于线程安全
     */
    private static final Object LOCK = new Object();



    @Override
    public String createReportOrder(ReportOrderCreateVo createVo) {
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        String userId = Objects.isNull(tokenInfo.getLoginId())?"":tokenInfo.getLoginId().toString();
        //生成订单号
        String s = generateOrderNumber();
        ReportOrder reportOrder = new ReportOrder();
        BeanUtils.copyProperties(createVo, reportOrder);
        reportOrder.setOrderNumber(s);
        LocalDateTime time = addTime(Duration.ofMinutes(5L));
        reportOrder.setExpireTime(time);
        reportOrderMapper.insert(reportOrder);
        return reportOrder.getOrderNumber();
    }

    @Override
    public ReportOrderRespVo selectByOddNum(String orderNumber) {
        ReportOrder reportOrder = new ReportOrder();
        reportOrder.setOrderNumber(orderNumber);
        List<ReportOrder> reportOrders = reportOrderMapper.selectList(reportOrder);
        if (CollectionUtils.isNotEmpty(reportOrders)) {
            ReportOrderRespVo convert = ReportOrderConvert.INSTANCE.convert(reportOrders.get(0));
            return convert;
        }
        return null;
    }

    @Override
    public PageResult<ReportOrderRespVo> selectPage(QueryOrderPageReq req) {
        PageResult<ReportOrderRespVo> reportOrderRespVoPageResult = ReportOrderConvert.INSTANCE.convertPage(reportOrderMapper.selectPage(req));
        return reportOrderRespVoPageResult;
    }

    @Override
    public CommonResult toRefundOrder(String orderNumber) {
        List<ReportOrder> orderList = reportOrderMapper.selectList("order_number", orderNumber);
        if (CollectionUtils.isEmpty(orderList)) {
            throw new MyException(ErrorCodeConstants.ORDER_NOT_FOUND.getCode(), ErrorCodeConstants.ORDER_NOT_FOUND.getMsg());
        }
        ReportOrder reportOrder = orderList.get(0);
        if (!Objects.equals(reportOrder.getOrderStatus(), PayOrderStatusRespEnum.SUCCESS.getStatus())) {
            throw new MyException(ErrorCodeConstants.PAY_ORDER_STATUS_IS_NOT_SUCCESS.getCode(), ErrorCodeConstants.PAY_ORDER_STATUS_IS_NOT_SUCCESS.getMsg());
        }
        //修改订单状态为审核中
        reportOrder.setOrderStatus(PayOrderStatusRespEnum.AUDIT.getStatus());
        reportOrder.setRefundTime(LocalDateTime.now());
        reportOrderMapper.updateByOrderId(orderNumber, reportOrder);
        return CommonResult.success("审核成功");
    }

    @Override
    public CommonResult confirmRefundOrder(ConfirmRefundOrder refundOrder) {
        ReportOrder reportOrder = new ReportOrder();
        reportOrder.setOrderNumber(refundOrder.getOrderNumber());
        List<ReportOrder> list = reportOrderMapper.selectList(reportOrder);
        if(CollectionUtils.isEmpty(list)){
            return CommonResult.error("订单不存在");
        }
        ReportOrder order = list.get(0);
        if (!Objects.equals(order.getOrderStatus(), PayOrderStatusRespEnum.AUDIT.getStatus())) {
            throw new MyException("退款审核失败，不是待退款状态");
        }
        if (refundOrder.getFlag() == 1) {
            log.info("退款审核通过，发起退款处理");
            return refundOrder(order.getId(), refundOrder.getAmount());
        } else {
            order.setOrderStatus(PayOrderStatusRespEnum.SUCCESS.getStatus());
            order.setRemarks(refundOrder.getMessage());
            log.info("订单号{}退款审核拒绝,拒绝理由是{}",refundOrder.getOrderNumber(),refundOrder.getMessage());
            reportOrderMapper.updateById(order);
        }
        return CommonResult.success(true);
    }

    @Override
    public CommonResult refundOrder(String orderNumber) {
        //查询订单信息
        List<ReportOrder> orderList = reportOrderMapper.selectList("order_number", orderNumber);
        if (CollectionUtils.isEmpty(orderList)) {
            throw new MyException(ErrorCodeConstants.ORDER_NOT_FOUND.getCode(), ErrorCodeConstants.ORDER_NOT_FOUND.getMsg());
        }
        ReportOrder reportOrder = orderList.get(0);
        //订单必须是支付成功的才允许退款
        if (!Objects.equals(reportOrder.getOrderStatus(), PayOrderStatusRespEnum.SUCCESS.getStatus())) {
            throw new MyException(ErrorCodeConstants.PAY_ORDER_STATUS_IS_NOT_SUCCESS.getCode(), ErrorCodeConstants.PAY_ORDER_STATUS_IS_NOT_SUCCESS.getMsg());
        }
        return refundOrder(reportOrder.getId(), reportOrder.getAmount());
    }

    private CommonResult refundOrder(String id, Long amount) {
        ReportOrder reserveOrderDO = reportOrderMapper.selectById(id);
        if (!Objects.equals(reserveOrderDO.getOrderStatus(), PayOrderStatusRespEnum.SUCCESS.getStatus())) {
            throw new MyException("退款失败，订单不是支付成功状态！");
        }
        try {
            reserveOrderDO.setOrderStatus(PayOrderStatusRespEnum.REFUNDING.getStatus());
            reportOrderMapper.updateById(reserveOrderDO);
//            //推送取消订单  先校验订单是否存在或者是否不是支付成功状态和已是退款状态
//            PayOrderDO order = validateOrderCanRefund(reserveOrderDO.getPayOrderId());
//            // 2.1 创建退款单
//            String payRefundId = payRefundApi.createPayRefund(new PayRefundCreateReqDTO()
//                    .setAppId(PAY_APP_ID).setUserIp(getClientIP())
//                    .setPayOrderId(reserveOrderDO.getPayOrderId())
//                    .setReason("订单退款")
//                    .setAmount(amount != null ? Long.valueOf(amount.toString()) : Long.valueOf(reserveOrderDO.getAmount().toString()))
//                    .setOriginAmount(Integer.valueOf(reserveOrderDO.getAmount().toString())));
            // 2.2 更新退款单到  订单
            reserveOrderDO.setRefundOrderId("1");
            reportOrderMapper.updateById(reserveOrderDO);
        } catch (Exception e) {
            reserveOrderDO.setOrderStatus(PayOrderStatusRespEnum.SUCCESS.getStatus());
            reportOrderMapper.updateById(reserveOrderDO);
            e.printStackTrace();
            return CommonResult.error(111, "退款失败");
        }
        return CommonResult.success(true);
    }
    /**
     * 生成订单号
     *
     * @return 订单号字符串
     */
    public static String generateOrderNumber() {
        synchronized (LOCK) {
            // 获取当前时间戳，并格式化为字符串
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String timestamp = sdf.format(new Date());
            String randomNumeric = RandomStringUtils.randomNumeric(RANDOM_LENGTH);
            // 拼接前缀、时间戳和随机数
            String orderNumber = PREFIX + timestamp + randomNumeric;
            return orderNumber;
        }
    }

//    private PayOrderDO validateOrderCanRefund(String id) {
//        // 校验订单是否存在
//        PayOrderDO order = orderMapper.selectById(id);
//        if (order == null) {
//            throw new MyException(ErrorCodeConstants.PAY_ORDER_NOT_FOUND.getCode(),ErrorCodeConstants.PAY_ORDER_NOT_FOUND.getMsg());
//        }
//        // 校验订单是否支付
//        if (!Objects.equals(order.getStatus(), PayOrderStatusEnum.SUCCESS.getStatus())) {
//            throw new MyException(ErrorCodeConstants.PAY_ORDER_REFUND_FAIL_NOT_PAID.getCode(),ErrorCodeConstants.PAY_ORDER_REFUND_FAIL_NOT_PAID.getMsg());
//        }
//        // 校验订单是否已退款
//        if (!Objects.equals(order.getRefundStatus(), PayRefundTypeEnum.NO.getStatus())) {
//            throw new MyException(ErrorCodeConstants.PAY_ORDER_REFUND_FAIL_REFUNDED.getCode(),ErrorCodeConstants.PAY_ORDER_REFUND_FAIL_REFUNDED.getMsg());
//        }
//        return order;
//    }
}
